import { Button, Card, Form, Input, InputNumber, Select, Space, message } from "antd"
import { Container, Content, Footer, SubTitle } from "./styles"
import { useEffect, useState } from "react";
import { useRequest } from "ahooks";
import GoodInfo from './components/GoodInfo'
import { useModel, history } from '@umijs/max'
import { PointsGoodsState, PointsGoodsType } from "@/constants/enums/goods";
import { getGoodsCoupon, queyGoodsDetail, savePointsGoodsBatch } from "@/services/goods";
import ImageGroup, { ImageGroupValidator } from "@/components/FormItems/ImageGroup";
import { getGoodsStock, queryCategory } from "@/services/common";
import { CategoryType } from "@/constants/enums/category";
import { getJumpParams } from "@/utils/common";
import { getCouponDetail } from "@/services/marketing/coupon";

const goodInfoValidator = (_: any, value: any) => {
  if (!value.data) {
    if (value.type === PointsGoodsType.优惠券) {
      return Promise.reject(new Error('请添加商品优惠券'))
    }
    if (value.type === PointsGoodsType.充电优惠券) {
      return Promise.reject(new Error('请添加充电优惠券'))
    }
    return Promise.reject(new Error('请添加商品'))
  } else {
    return Promise.resolve()
  }
}

const PointGoodEdit: React.FC = () => {
  const [pointsForm] = Form.useForm()
  const { closeCurrentTab } = useModel('global')
  const saveReq = useRequest(savePointsGoodsBatch, {manual: true})
  const category = useRequest(() => queryCategory({type: CategoryType.积分商城}))
  const [disabled, setDisabled] = useState(false)
  const goodsDetail = useRequest(queyGoodsDetail, {manual: true})
  const [inventory, setInventory] = useState(0)
  const goodsInventory = useRequest(getGoodsStock, {manual: true})
  const chargeCouponInventory = useRequest(getCouponDetail, {manual: true})
  const goodsCouponInventory = useRequest(getGoodsCoupon, {manual: true})

  const submit = () => {
    pointsForm.validateFields()
    .then((values: any) => {
      if (values.num > values.goodInfo.data.inventory) {
        message.error('兑换数量不可大于可用库存数量')
        return
      }
      const _params = {
        integralId: values.integralId,
        img: values.img.map((it: any) => it.source).join(','),
        type: values.goodInfo.type,
        goodsId: values.goodInfo.data.id,
        goodsName: values.goodInfo.data.name,
        goodsDetail: JSON.stringify(values.goodsDetail),
        integralInfo: JSON.stringify({content: values.goodInfo.data.content, inventory: values.goodInfo.data.inventory, explain: values.explain}),
        category: values.category,
        goodsPrice: values.goodsPrice,
        integralPrice: values.integralPrice,
        num: values.num,
        purchaseNum: values.purchaseNum,
        state: values.state,
      }
      saveReq.runAsync({reqList: [_params]})
      .then(() => {
        const event = new CustomEvent('refreshPointsGoodsList')
        window.dispatchEvent(event)
        message.success('保存成功')
        closeCurrentTab()
      })
    })
  }
  const getGoodsDetail = (goodsId: string) => {
    goodsDetail.runAsync({id: goodsId}).then(res => {
      pointsForm.setFieldsValue({
        img: JSON.parse(res.data.goodsShow),
        goodsDetail: JSON.parse(res.data.goodsDetail)
      })
    })
  }
  const onValuesChange = (changeValue: any) => {
    console.log(changeValue)
    if (changeValue.goodInfo) {
      setInventory(changeValue.goodInfo?.data?.inventory || 0)
    }
    if (changeValue.goodInfo?.type === 'Goods') {
      if (changeValue.goodInfo.data) {
        getGoodsDetail(changeValue.goodInfo.data.goodsId)
      }
    } else if (changeValue.goodInfo?.type === 'Charge_Coupon' || changeValue.goodInfo?.type === 'Coupon') {
    }
  }
  const getGoodsInventory = async (_data: any) => {
    console.log('_content', _data)
    const _content = JSON.parse(_data.integralInfo)
    let _inventory = _data.num
    if (_data.type === PointsGoodsType.充电优惠券) {
      const res: any = await chargeCouponInventory.runAsync({id: _data.goodsId})
      _inventory = _data.num + (res.data.num || 0) - (res.data.sendNum || 0)
    } else if (_data.type === PointsGoodsType.优惠券) {
      const res: any = await goodsCouponInventory.runAsync(_data.goodsId)
      _inventory = _data.num + (res.data.num || 0) - (res.data.alreadyReceivedNum || 0)
    } else if (_data.type === PointsGoodsType.商品) {
      const res: any = await goodsInventory.runAsync(_data.goodsId)
      _inventory = _data.num + (res.data.stockNum || 0)
    }
    setInventory(_inventory)
    pointsForm.setFieldsValue({
      goodInfo: {
        type: _data.type,
        data: {
          id: _data.goodsId,
          name: _data.goodsName,
          content: _content.content,
          inventory: _inventory,
        },
      }
    })
  }

  useEffect(() => {
    const _data = getJumpParams()
    if (_data) {
      setDisabled(true)
      const _content = JSON.parse(_data.integralInfo)
      pointsForm.setFieldsValue({
        integralId: _data.integralId,
        img: _data.img.split(',').map((it: any) => ({source: it, type: 'Image'})),
        goodInfo: {
          type: _data.type,
          data: {
            id: _data.goodsId,
            name: _data.goodsName,
            content: _content.content,
            inventory: _content.inventory,
          },
        },
        // goodsDetail: JSON.parse(_data.goodsDetail),
        explain: _content.explain,
        category: _data.category,
        goodsPrice: _data.goodsPrice,
        integralPrice: _data.integralPrice,
        num: _data.num,
        purchaseNum: _data.purchaseNum,
        state: _data.state,
      })
      getGoodsInventory(_data)
    } else {
      pointsForm.setFieldsValue({
        integralId: '',
        img: [],
        goodInfo: {
          type: PointsGoodsType.充电优惠券,
        },
        goodsDetail: undefined,
        category: undefined,
        integralPrice: 100,
        num: undefined,
        purchaseNum: undefined,
        goodsPrice: 0,
        explain: '',
        state: PointsGoodsState.下架,
      })
    }
  }, [])

  return (
    <Container>
      <Content>
        <Form form={pointsForm} name='pointsForm' labelCol={{flex: '120px'}} onValuesChange={onValuesChange}>
          <Form.Item noStyle name='integralId'><Input hidden /></Form.Item>
          <Form.Item noStyle name='state'><Input hidden /></Form.Item>
          <Card styles={{body: {padding: '18px 24px'}}}>
            <SubTitle>基本信息</SubTitle>
            <Form.Item label='选择商品' required name='goodInfo' rules={[{validator: goodInfoValidator}]}>
              <GoodInfo disabled={disabled} />
            </Form.Item>
            <Form.Item label='商品图片' name='img' required rules={[{validator: (_, val) => ImageGroupValidator('请上传商品图片', val)}]}>
              <ImageGroup max={9} style={{width: 600}} sortable={false} />
            </Form.Item>
            {/* <Access accessible={goodsType === 'physical'}>
              <Form.Item label='商品详情' name='goodsDetail' required rules={[{validator: (_, val) => ImageGroupValidator('请上传商品详情图片', val)}]}>
                <ImageGroup max={5} style={{width: 320}} tips={['最多可上传 5 张图片']} />
              </Form.Item>
            </Access> */}
            <Form.Item label='商品分组' required>
              <Space>
                <Form.Item noStyle name='category' rules={[{required: true, message: '请选择商品分组'}]}>
                  <Select
                    placeholder="请选择" style={{width: 320}} loading={category.loading}
                    options={category.data?.data.map(it => ({label: it.categoryName, value: it.categoryId}))}
                  />
                </Form.Item>
                <a onClick={() => history.push('/mall/points/group')}>新建</a>
                <div>|</div>
                <a onClick={() => category.refresh()}>刷新</a>
              </Space>
            </Form.Item>
            <Form.Item label='权益说明' name='explain' rules={[{required: true, message: '请输入权益说明'}]}>
              <Input.TextArea placeholder="请输入" style={{width: 320, height: 200}} />
            </Form.Item>
          </Card>
          <Card styles={{body: {padding: '18px 24px'}}} style={{marginTop: 16}}>
            <SubTitle>兑换条件</SubTitle>
            <Form.Item label='兑换价' required>
              <div className="flex gap-2 items-center">
                <Form.Item name='integralPrice' noStyle rules={[{required: true, message: '请填写兑换价'}]}>
                  <InputNumber
                    placeholder="请输入"
                    controls={false}
                    min={1}
                    precision={0}
                    style={{width: 120}}
                    suffix='积分'
                  />
                </Form.Item>
                <span>+</span>
                <Form.Item name='goodsPrice' noStyle>
                  <InputNumber
                    placeholder="请输入"
                    controls={false}
                    min={0}
                    precision={2}
                    style={{width: 120}}
                    suffix='元'
                  />
                </Form.Item>
              </div>
            </Form.Item>
            <Form.Item label='兑换数量'>
              <div className="flex items-center">
                <Form.Item name='num' rules={[{required: true, message: '请填写兑换数量'}]} noStyle>
                  <InputNumber
                    placeholder="请输入"
                    controls={false}
                    min={0}
                    max={inventory}
                    precision={0}
                    style={{width: 120}}
                    suffix='个'
                />
                </Form.Item>
                <div style={{fontSize:12,color:'#888888',marginLeft:12}}>剩余库存：{inventory}</div>
              </div>
            </Form.Item>
            <Form.Item label='兑换限制' name='purchaseNum' rules={[{required: true, message: '请填写兑换限制'}]}>
              <InputNumber
                placeholder="请输入"
                controls={false}
                min={1}
                precision={0}
                style={{width: 120}}
                suffix='个/人'
              />
            </Form.Item>
          </Card>
        </Form>
      </Content>
      <Footer>
        <Button style={{height: 34}} type="primary" onClick={submit} loading={saveReq.loading}>保存</Button>
      </Footer>
    </Container>
  )
}

export default PointGoodEdit
